package com.learn.temp.api;

/**
 * @author wangxing
 * @version 2020/6/5 10:54 Administrator
 */
public class VolatileVisbilitySample {
    private volatile boolean initFlag = false;

    public void refresh() {
        this.initFlag = true;
        String threadName = Thread.currentThread().getName();
        System.out.println("thread :" + threadName +
                ": update shared variable initFlag");
    }

    public void load() {
        String threadName = Thread.currentThread().getName();
        while (!this.initFlag) {
            synchronized (this) {
            }
        }
        System.out.println("thread :" + threadName +
                ";current thread sniffing initFlag  status change");
    }

    private static volatile int num = 0;

    public static void increase() {
        num++;
    }

    /**
     * 线程可见性验证
     */
    public void threadVolatile() {
        Thread thread1 = new Thread(() -> load(), "thread1");
        thread1.start();
        Thread thread2 = new Thread(() -> refresh(), "thread1");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
    }

    private volatile int counter = 0;

    /**
     * 原子性验证
     */
    public void threadAtomicity() {
        for (int j = 0; j < 10; j++) {
            Thread t = new Thread(() -> {
                synchronized (this) {
                    for (int k = 0; k < 1000; k++) {
                        counter++;
                    }
                }
            }
            );
            t.start();
        }
        System.out.println(counter);

    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            VolatileVisbilitySample v = new VolatileVisbilitySample();
            v.threadAtomicity();
        }
    }


}
